package com.yogee.topseller.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.tsy.sdk.pay.weixin.WXPay;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.AppManager;
import com.yogee.core.utils.NetUtil;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.MainActivity;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.base.HttpActivity;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import com.tsy.sdk.pay.alipay.Alipay;
import com.yogee.topseller.activity.login.view.impl.RegisterLabelActivity;
import com.yogee.topseller.adapter.HuiyuanAdapter;
import com.yogee.topseller.bean.HuiyuanListModel;
import com.yogee.topseller.bean.HuiyuanModel;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.http.Config;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.TitleLayout;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/3/7.
 */

public class PayActivity extends HttpActivity {

    @BindView(R.id.title)
    TitleLayout title;
    @BindView(R.id.huiyuan_rv)
    RecyclerView huiyuan_rv;
    @BindView(R.id.img_wx_select)
    ImageView img_wx_select;
    @BindView(R.id.img_alipay_select)
    ImageView img_alipay_select;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.img_ad)
    ImageView img_ad;

    HuiyuanAdapter mAdapter;
    private String currentImg="";
    private String currentUrl="";
    private int type=0;

    private String select = "";

    private List<HuiyuanModel> list = new ArrayList<>();
    // 选中的会员
    private HuiyuanModel modelSelect;

    int payType = 0; // 0 微信支付  1  支付宝

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initView() {

        title.setTitle("我的订单");
        title.setActivity(this);
        select = getIntent().getStringExtra("select");

        huiyuan_rv.setLayoutManager(new LinearLayoutManager(this));
        huiyuan_rv.setHasFixedSize(true);
        mAdapter = new HuiyuanAdapter(this);
        mAdapter.setListener(listener);
        huiyuan_rv.setAdapter(mAdapter);

        initData();
    }

    /**
     * 选中监听
     */
    Listener listener = new Listener() {
        @Override
        public void getSelect(HuiyuanModel model) {
            modelSelect = model;
            tv_money.setVisibility(View.VISIBLE);
            tv_money.setText("￥ "+model.getPrice());
            currentImg = model.getImgs();
            currentUrl = model.getPayImg();
            if(model.getMonth().equals("1")){
                type=0;
            }else{
                type=1;
            }
//            Glide.with(PayActivity.this).load(currentImg).into(img_ad);
        }
    };

    /**
     * 数据初始化
     */
    private void initData(){
        HttpManager.getInstance().gethuiyuanList(AppUtil.getUserId(PayActivity.this)).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<HuiyuanListModel>() {
            @Override
            public void onNext(HuiyuanListModel o) {
                list = o.getList();
                LogUtils.e("payimg","payImg:"+o.getPayImg());

                currentImg = o.getList().get(0).getImgs();
                currentUrl = o.getList().get(0).getPayImg();
                Glide.with(PayActivity.this).load(o.getPayImg()).into(img_ad);
                if(TextUtils.isEmpty(select))
                    mAdapter.addData(o.getList());
                else{
                    mAdapter.setSelect(o.getList(),o.getList().size()-1);
                    modelSelect = o.getList().get(o.getList().size()-1);
                    tv_money.setVisibility(View.VISIBLE);
                    tv_money.setText("￥ "+modelSelect.getPrice());
                    currentImg = modelSelect.getImgs();
                    currentUrl = modelSelect.getPayImg();
//                    Glide.with(PayActivity.this).load(o.getPayImg()).into(img_ad);
                }

            }
        }, this));
    }


    @OnClick({R.id.img_ad,R.id.btn_alipay,R.id.btn_wx,R.id.rl_wx_pay,R.id.rl_alipay_pay,R.id.ll_bottom})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.img_ad:
                startActivity(new Intent(PayActivity.this, HyqxActivity.class).putExtra("url",currentUrl).putExtra("type",type));

                break;
            case R.id.btn_alipay:
//                doAlipay("alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2016080800194337&biz_content=%7B%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%2220180306001122335%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22App%E6%94%AF%E4%BB%98%E6%B5%8B%E8%AF%95Java%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=%E5%95%86%E6%88%B7%E5%A4%96%E7%BD%91%E5%8F%AF%E4%BB%A5%E8%AE%BF%E9%97%AE%E7%9A%84%E5%BC%82%E6%AD%A5%E5%9C%B0%E5%9D%80&sign=VWR2ss8Bq3XUWBB0tQUmysw8lbOAdMv6Ad5uoLlS0FJgYtOevq5CoclwutmpEL2kpMW%2FHV%2BlWRKA3jYCA%2BBdmCB1axfiAGGbv5MlD%2Fx4VT58L0oj9v1J947CSBSUnJtF0D3xVpSjydgd7Kdqr5v0ETEb4%2BT3Rr1MFc47hD0d5Us2%2FWyG2IFuSOwAsA0ynAjGYaq0TQisfDPJWwfza0ahnetDxZOlQuDBFPtyckPVS73Pe%2FsLltODSSZNuDni9YVzTLUc6ivlh4VvyvT465Lb39Rndaa8cWbc%2BHACuyCz4%2B9rdgSfh%2B0vVZcZvA1EM6uPKa2QXJE1keROThJhZCfYtw%3D%3D&sign_type=RSA2&timestamp=2018-03-06+17%3A26%3A55&version=1.0");
//                alipay();
                break;
            case R.id.btn_wx:
                ToastUtils.showToast(PayActivity.this,"微信");
                break;
            case R.id.ll_bottom:
                // 支付
                if(modelSelect==null){
                    ToastUtils.showToast(PayActivity.this,"请选择充值会员类型");
                }else{
                    if(payType==1)
                        alipay(AppUtil.getUserId(PayActivity.this),modelSelect.getId());
                    else
//                        ToastUtils.showToast(PayActivity.this,"微信支付");
                        wxpay(AppUtil.getUserId(PayActivity.this),modelSelect.getId());
                }

                break;
            case R.id.rl_wx_pay:
                img_wx_select.setImageResource(R.drawable.select1);
                img_alipay_select.setImageResource(R.drawable.unselect1);
                payType = 0;
//                ToastUtils.showToast(PayActivity.this,"微信支付");
                break;
            case R.id.rl_alipay_pay:
                img_alipay_select.setImageResource(R.drawable.select1);
                img_wx_select.setImageResource(R.drawable.unselect1);
                payType = 1;
//                ToastUtils.showToast(PayActivity.this,"支付宝支付");
                break;

        }

    }

    private void alipay(String userId,String id){
        pd.show();
        HttpManager.getInstance().alipay(userId,id).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                pd.dismiss();
                doAlipay(o.getData());

            }
        }, this));
    }

    /**
     * 微信支付
     * @param userId
     * @param id
     */
    private void wxpay(String userId,String id){
        {
            if (!NetUtil.isNetworkAvailable()) {
                ToastUtils.showToast(PayActivity.this, "网络中断了，请重新链接网络。");
                return;
            }
            if(pd!=null)
                pd.show();

            //组装调取银行卡验证api的数据
            JSONObject object = new JSONObject();
            try {
                object.put("userId", userId);
                object.put("id", id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //网络调取api
//        OkHttpClient okHttpClient = new OkHttpClient();

            OkHttpClient okHttpClient =
                    new OkHttpClient.Builder()
                            .readTimeout(60, TimeUnit.SECONDS)//设置读取超时时间
                            .writeTimeout(60,TimeUnit.SECONDS)//设置写的超时时间
                            .connectTimeout(60,TimeUnit.SECONDS)//设置连接超时时间
                            .build();
            Request.Builder builder = new Request.Builder();
            RequestBody requestBody = RequestBody
                    .create(MediaType.parse("text/plain;chaset=utf-8"), object.toString());
            Request request = builder.post(requestBody)
                    .url(Config.BASE_URL+"pay/payparm")
//                .addHeader("Authorization", "APPCODE " + appCode)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onFailure(Call call, final IOException e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                        //失败处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }
                            if(pd!=null)
                                pd.dismiss();
                            ToastUtils.showToast(PayActivity.this, " 请求失败");
                        }
                    });
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
//                        //成功处理
//                        if (progressBar.isShowing()){
//                            progressBar.dismiss();
//                        }
                            pd.dismiss();
                            //组装json来回显银行卡号
                            try {
                                Gson gson = new Gson();
                                String result = response.body().string().replace("\n","");
                                LogUtils.e("success",result);
                                JSONObject jsonObject = new JSONObject(result);
                                doWXPay(jsonObject.getJSONObject("data"));

                            } catch (Exception e) {
                                ToastUtils.showToast(PayActivity.this, "支付失败");
                                LogUtils.e("fail",e.toString());
                            }
                        }
                    });
                }
            });
        }
    }
    /**
     * 支付宝支付
     * @param pay_param 支付服务生成的支付参数
     */
    private void doAlipay(String pay_param) {


        new Alipay(this, pay_param, new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                Toast.makeText(getApplication(), "支付成功", Toast.LENGTH_SHORT).show();
                PayActivity.this.finish();
            }

            @Override
            public void onDealing() {
                Toast.makeText(getApplication(), "支付处理中...", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        Toast.makeText(getApplication(), "支付失败:支付结果解析错误", Toast.LENGTH_SHORT).show();
                        break;

                    case Alipay.ERROR_NETWORK:
                        Toast.makeText(getApplication(), "支付失败:网络连接错误", Toast.LENGTH_SHORT).show();
                        break;

                    case Alipay.ERROR_PAY:
                        Toast.makeText(getApplication(), "支付错误:支付码支付失败", Toast.LENGTH_SHORT).show();
                        break;

                    default:
                        Toast.makeText(getApplication(), "支付错误", Toast.LENGTH_SHORT).show();
                        break;
                }

            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplication(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        }).doPay();
    }


    /**
     * 微信支付
     * @param pay_param 支付服务生成的支付参数
     */
    private void doWXPay(JSONObject pay_param) {
        LogUtils.e("sfz","参数"+pay_param);
        String wx_appid = "wxb6242301ba0b55a6";     //替换为自己的appid
        WXPay.init(getApplicationContext(), wx_appid);      //要在支付前调用
        WXPay.getInstance().doPay(pay_param, new WXPay.WXPayResultCallBack() {
            @Override
            public void onSuccess() {
                Toast.makeText(getApplication(), "支付成功", Toast.LENGTH_SHORT).show();
                PayActivity.this.finish();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        Toast.makeText(getApplication(), "未安装微信或微信版本过低", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY_PARAM:
                        Toast.makeText(getApplication(), "参数错误", Toast.LENGTH_SHORT).show();
                        break;

                    case WXPay.ERROR_PAY:
                        Toast.makeText(getApplication(), "支付失败", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onCancel() {
                Toast.makeText(getApplication(), "支付取消", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public interface Listener{
        void getSelect(HuiyuanModel model);
    }

    @Override
    public void showMsg(String msg) {
        super.showMsg(msg);
        LogUtils.e("showMsg","showMsg:"+msg);
    }
}
